package com.pqc.tbk.service.account;

import java.io.Serializable;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.pqc.tbk.entity.account.Group;
import com.pqc.tbk.entity.account.User;

@Component
public class ShiroDbRealm extends AuthorizingRealm {

	private AccountManager accountManager;

	public ShiroDbRealm() {
		super();
		// 设置认证token的实现类
		setAuthenticationTokenClass(UsernamePasswordToken.class);
		// 设置加密算法
		setCredentialsMatcher(new HashedCredentialsMatcher(
				Md5Hash.ALGORITHM_NAME));
	}

	/**
	 * 认证回调函数, 登录时调用.
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			final AuthenticationToken authcToken)
			throws AuthenticationException {
		final UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		final User user = accountManager.findByUserName(token.getUsername());
		if (user != null) {
			return new SimpleAuthenticationInfo(new ShiroUser(user.getId(),
					user.getUsername(), user.getNick()), user.getPassword(),
					getName());
		} else {
			return null;
		}
	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			final PrincipalCollection principals) {
		principals.fromRealm(getName()).iterator().next();
		final ShiroUser shiroUser = (ShiroUser) principals.fromRealm(getName())
				.iterator().next();
		final User user = accountManager.findByUserName(shiroUser
				.getLoginName());
		if (user != null) {
			final SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			for (final Group group : user.getGroupList()) {
				// 基于Permission的权限信息
				info.addStringPermissions(group.getPermissionList());
				info.addRole(group.getName());
			}
			return info;
		} else {
			return null;
		}
	}

	/**
	 * 更新用户授权信息缓存.
	 */
	public void clearCachedAuthorizationInfo(final String principal) {
		final SimplePrincipalCollection principals = new SimplePrincipalCollection(
				principal, getName());
		clearCachedAuthorizationInfo(principals);
	}

	/**
	 * 清除所有用户授权信息缓存.
	 */
	public void clearAllCachedAuthorizationInfo() {
		final Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
		if (cache != null) {
			for (final Object key : cache.keys()) {
				cache.remove(key);
			}
		}
	}

	@Autowired
	public void setAccountManager(final AccountManager accountManager) {
		this.accountManager = accountManager;
	}

	/**
	 * 自定义Authentication对象，使得Subject除了携带用户的登录名外还可以携带更多信息.
	 */
	public static class ShiroUser implements Serializable {

		private static final long serialVersionUID = -1748602382963711884L;
		private final String loginName;
		private final String nick;
		private final Long id;

		public ShiroUser(final Long id, final String loginName,
				final String nick) {
			this.id = id;
			this.loginName = loginName;
			this.nick = nick;
		}

		public String getNick() {
			return nick;
		}

		public String getLoginName() {
			return loginName;
		}

		/**
		 * 本函数输出将作为默认的<shiro:principal/>输出.
		 */
		@Override
		public String toString() {
			return loginName;
		}

		public String getName() {
			return nick;
		}

		public Long getId() {
			return id;
		}

	}
}
